const { query, run } = require('../database/db');
const bcrypt = require('bcryptjs');

// 创建用户
async function createUser(userData) {
    const { username, password, email, name, phone, address } = userData;
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const result = await run(
        'INSERT INTO users (username, password, email, name, phone, address) VALUES (?, ?, ?, ?, ?, ?)',
        [username, hashedPassword, email, name, phone, address]
    );
    
    return result.lastID;
}

// 根据用户名查找用户
async function findUserByUsername(username) {
    const users = await query('SELECT * FROM users WHERE username = ?', [username]);
    return users[0];
}

// 验证用户密码
async function verifyPassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
}

// 更新用户信息
async function updateUser(userId, userData) {
    const { name, phone, address } = userData;
    await run(
        'UPDATE users SET name = ?, phone = ?, address = ? WHERE id = ?',
        [name, phone, address, userId]
    );
}

// 获取所有用户（管理员功能）
async function getAllUsers() {
    return await query('SELECT id, username, email, name, phone, address, role, created_at FROM users');
}

// 删除用户（管理员功能）
async function deleteUser(userId) {
    await run('DELETE FROM users WHERE id = ?', [userId]);
}

module.exports = {
    createUser,
    findUserByUsername,
    verifyPassword,
    updateUser,
    getAllUsers,
    deleteUser
}; 